#include "timer.h"
#include "mhscpu_timer.h"


#define TICKS		2
volatile uint32_t tick[TICKS];
volatile uint32_t ticken[TICKS];

static SYSCTRL_ClocksTypeDef clocks;

void timer_init(void)
{
	TIM_InitTypeDef s;
	SYSCTRL_GetClocksFreq(&clocks);
	s.TIMx = TIM_0;
	s.TIM_Period = clocks.PCLK_Frequency / 1000;
	
	TIM_Init(TIMM0, &s);
	TIM_ITConfig(TIMM0, TIM_0, ENABLE);
}

void timer_init_ms(uint32_t ms)
{
	TIM_InitTypeDef s;
	SYSCTRL_GetClocksFreq(&clocks);
	s.TIMx = TIM_0;
	s.TIM_Period = (clocks.PCLK_Frequency / 1000 * ms);

	TIM_DeInit(TIMM0);
	TIM_Cmd(TIMM0, TIM_0, DISABLE);
	TIM_Init(TIMM0, &s);
	TIM_ITConfig(TIMM0, TIM_0, ENABLE);
}

void timer_start(uint32_t num)
{
	ticken[num] = 1;
	TIM_Cmd(TIMM0, TIM_0, ENABLE);
}

void timer_stop(void)
{
	TIM_Cmd(TIMM0, TIM_0, DISABLE);
}

void timer_pause(uint32_t num)
{
	ticken[num] = 0;
}

uint32_t timer_tick(uint32_t num)
{
	uint32_t ret;
	ticken[num] = 0;
	ret = tick[num];
	tick[num] = 0;
	return ret;
}

uint32_t timer_us(uint32_t num,  uint32_t ms_per, uint32_t pclk_fre)
{
	volatile uint32_t us;
	us = timer_counter() / (pclk_fre / (1000000 * ms_per));
	us += timer_tick(num) * 1000 * ms_per;
	return us;
}

uint32_t timer_counter(void)
{
	return (TIMM0->TIM[TIM_0].LoadCount - TIMM0->TIM[TIM_0].CurrentValue);
}


void TIM0_0_IRQHandler(void)
{
	uint32_t i = TICKS;
	while(i)
	{
		if(ticken[i - 1])
			tick[i - 1]++;
		i--;
	}
	TIM_ClearITPendingBit(TIMM0, TIM_0);
}

